//
//  UIPlaceHolderTextView.m
//  SMealUserSide
//
//  Created by apple on 2018/2/22.
//  Copyright © 2018年 yaozhengzheng. All rights reserved.
//

#import "UIPlaceHolderTextView.h"

@interface  UIPlaceHolderTextView()<UITextViewDelegate>

@property (nonatomic, strong) UILabel *placeHolderLabel;

@end

@implementation UIPlaceHolderTextView
- (instancetype)initWithFrame:(CGRect)frame
{
    if(self = [super initWithFrame:frame])
    {
        [self addSubview:self.placeHolderLabel];
        self.delegate = self;
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    WS(ws);
    
    CGFloat topDefaultMargin = 6;
    CGFloat leftDefaultMargin = 3;
    [self.placeHolderLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(ws).offset(topDefaultMargin);
        make.left.equalTo(ws).offset(leftDefaultMargin);
        make.right.equalTo(ws);
    }];
}

- (void)setPlaceHolderOffset:(UIOffset)placeHolderOffset
{
    _placeHolderOffset = placeHolderOffset;
    //设置光标位置
    self.selectedRange = NSMakeRange(placeHolderOffset.horizontal, 0);
    self.contentInset = UIEdgeInsetsMake(placeHolderOffset.vertical, placeHolderOffset.horizontal, placeHolderOffset.vertical, placeHolderOffset.horizontal); // 内容的位置
    [self layoutIfNeeded];
    [self setNeedsLayout];
   
}

- (void)setPlaceHolder:(NSString *)placeHolder
{
    _placeHolder = placeHolder;
    self.placeHolderLabel.hidden = placeHolder.length == 0;
    self.placeHolderLabel.text = placeHolder;
}

- (void)setPlaceHolderFont:(UIFont *)placeHolderFont
{
    _placeHolderFont = placeHolderFont;
    self.placeHolderLabel.font = placeHolderFont;
    self.font = self.placeHolderFont;
}

- (void)setPlaceHolderColor:(UIColor *)placeHolderColor
{
    _placeHolderColor = placeHolderColor;
    self.placeHolderLabel.textColor = placeHolderColor;
}


#pragma mark - delegate
- (void)textViewDidChange:(UITextView *)textView
{
    self.placeHolderLabel.hidden = textView.text.length > 0;
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]){ //判断输入的字是否是回车，即按下return
        //在这里做你响应return键的代码
        [self resignFirstResponder];
        return NO; //这里返回NO，就代表return键值失效，即页面上按下return，不会出现换行，如果为yes，则输入页面会换行
    }
    
    return YES;
}




#pragma mark - lazy
- (UILabel *)placeHolderLabel
{
    if(!_placeHolderLabel){
        _placeHolderLabel = [[UILabel alloc]init];
        _placeHolderLabel.textColor = ZBColorChangeRGB(0x777777, 1.0);
        _placeHolderLabel.font = [UIConstantFont getFontW6_H13];
    }
    return _placeHolderLabel;
}
@end
